<template>
    <van-nav-bar
      title="商品分类"
      left-text="返回"
      left-arrow
      @click-left="onClickLeft"
    />
  <!--导航栏-->
  <van-tree-select
    v-model:active-id="rightactiveId"
    v-model:main-active-index="leftactiveIndex"
    :items="categoryData"
  >

    <!--模板插值表达式-->
    <template #content>
      <!--九宫格的方式 加载图片-->
      <van-grid :column-num="3">
      <van-grid-item v-for="item in categoryData[leftactiveIndex]?.children" 
      :key="item.id" 
      :icon="item.img" 
      :text="item.text" :to="{name:'moveproduct',query:{categoryId:item.id}}"/>
    </van-grid>
    </template>
  </van-tree-select>
  

</template>
<script setup lang="ts">
import { onMounted, ref } from 'vue';
import { CategoryApi } from '@/api';
   const rightactiveId = ref(1);  //右侧选中项的 id
  const leftactiveIndex = ref(0); //左侧选中项的索引
const categoryData =ref([]);
const categoryData2 = ref([
  
  { id: 1, name: '手机',img: 'https://fastly.jsdelivr.net/npm/@vant/assets/apple-1.jpeg',parentId:0},
  { id: 2, name: '华为手机', img: 'https://fastly.jsdelivr.net/npm/@vant/assets/apple-1.jpeg', parentId: 1 },
  { id: 3, name: '三星手机', img: 'https://fastly.jsdelivr.net/npm/@vant/assets/apple-1.jpeg', parentId: 1 },
  { id: 4, name: '智能家居', img: 'https://fastly.jsdelivr.net/npm/@vant/assets/apple-1.jpeg', parentId: 0 },
  { id: 5, name: '窗帘', img: 'https://fastly.jsdelivr.net/npm/@vant/assets/apple-1.jpeg', parentId: 4 },
  { id: 6, name: '声控电灯', img: 'https://fastly.jsdelivr.net/npm/@vant/assets/apple-1.jpeg', parentId: 4 },
                                    
]);

onMounted(() => { 
  // categoryData2.value.forEach((item: any) => {
  //   item.text = item.name
  // })

  // let categoryData3 = categoryData2.value.reduce((newArray: any, currValue: any) => { 
  //   currValue.children = categoryData2.value.filter(
  //     item => { return item.parentId == currValue.id}
  //   )
  //   if (currValue.parentId === 0) { 
  //     newArray.push(currValue)
  //   }
  //   return newArray
  // },[])
  // console.log(categoryData3);
  // //把对应的id给匹配一下
  // categoryData.value = categoryData3
  callCategoryApi()
})
const callCategoryApi = () => { 

  CategoryApi.select.call().then((res: any) => { 
    console.log(res);
    res.forEach((item: any) => { 
      item.text = item.name;
    })
     let categoryData3 = res.reduce((newArray: any, currValue: any) => {
      currValue.children = res.filter(
        (item:any) => { return item.parentId == currValue.id }
      )
      if (currValue.parentId === 0) {
        newArray.push(currValue)
      }
      return newArray
    }, [])
    console.log(categoryData3);
    //把对应的id给匹配一下
    categoryData.value = categoryData3
  })
}


     const onClickLeft = () => history.back();
</script>
<style>

.van-icon__image{
  width: 70px !important;
  height: 70px !important;
  font-size: 20px !important;

}
.van-grid-item__text{
  font-size: 20px;
}

</style>